package com.example.service_order.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.common.commonsutils.JwtUtils;
import com.example.common.commonsutils.R;
import com.example.common.exception.GuliException;
import com.example.common.vo.CourseInfoVO;
import com.example.service_order.client.CourseClient;
import com.example.service_order.client.MemberClient;
import com.example.service_order.config.WXConfig;
import com.example.service_order.entity.Order;
import com.example.service_order.entity.vo.OrderVO;
import com.example.service_order.mapper.OrderMapper;
import com.example.service_order.service.OrderService;
import com.example.service_order.utils.OrderConstUtils;
import com.example.service_order.utils.OrderNoUtils;
import com.wechat.pay.java.core.Config;
import com.wechat.pay.java.service.payments.nativepay.NativePayService;
import com.wechat.pay.java.service.payments.nativepay.model.PrepayResponse;
import com.wechat.pay.java.service.payments.nativepay.model.Amount;
import com.wechat.pay.java.service.payments.nativepay.model.PrepayRequest;
import jakarta.annotation.Resource;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @Author:tjf
 * @Description:
 */
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {
    @Resource
    private OrderMapper orderMapper;
    @Resource(name = "stringRedisTemplate")
    private StringRedisTemplate redisTemplate;
    @Resource
    private MemberClient memberClient;
    @Resource
    private CourseClient courseClient;


    /**
     * 创建课程订单
     *
     * @param courseId
     * @param token
     * @return
     */
    @Override
    public String saveOrder(String courseId, String token) {
        Order order = new Order();
        // 从token中解析会员的信息
        String memberId = null;
        try {
            memberId = JwtUtils.getMemberIdByJwtToken(token);
        } catch (Exception e) {
            throw new GuliException(20001, "Token无效，请重新登录");
        }

        if (StringUtils.isBlank(memberId)) {
            return "";
        }
        // 该课程购买过了？
        LambdaQueryWrapper<Order> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Order::getCourseId,courseId)
                .eq(Order::getMemberId, memberId)
                .eq(Order::getStatus, OrderConstUtils.ORDER_PAID);
        if (orderMapper.selectCount(wrapper) > 0) {
            throw new GuliException(20001, "该课程已购买");
        }

        String key = OrderConstUtils.ORDER_KEY + courseId + ":" + memberId;
        // 存在未过期的订单号(未完成支付的)？
        Boolean orderNotExpire = redisTemplate.hasKey(key);
        if (orderNotExpire == true) {
            // 存在未支付的订单则返回未支付的订单号
            return redisTemplate.opsForValue().get(key);
        }
        // 查询用户的信息
        R response = memberClient.getMemberInfoById(memberId);
        if (response.getCode() != 20000) {
            throw new GuliException(20001, "会员服务异常，请稍后重试");
        }
        Map<String, Object> map = (Map<String, Object>) response.getData().get("memberInfo");

        // 查询课程的信息
        CourseInfoVO courseInfo = courseClient.queryCourseInfoForOrderById(courseId);
        if (courseInfo == null) {
            throw new GuliException(20001, "创建订单失败，该课程存在异常");
        }
        // 封装数据
        String orderNo = OrderNoUtils.getOrderNo();

        order.setMemberId(memberId);
        order.setMobile((String) map.get("mobile"));
        order.setNickname((String) map.get("nickname"));
        order.setCourseId(courseId);
        order.setCourseCover(courseInfo.getCover());
        order.setCourseTitle(courseInfo.getTitle());
        order.setOrderNo(orderNo);
        order.setTeacherName(courseInfo.getTeacherName());
        order.setPayType(OrderConstUtils.PAY_BY_WX);
        order.setTotalFee(courseInfo.getPrice());
        order.setStatus(OrderConstUtils.ORDER_UNPAID);

        // 插入数据库
        orderMapper.insert(order);
        // 在redis存入当前订单号
        redisTemplate.opsForValue().setIfAbsent(key, orderNo, 20, TimeUnit.MINUTES);
        // 返回订单号
        return orderNo;
    }

    /**
     * 根据订单号，查询课程订单
     *
     * @param orderNo
     * @return
     */
    @Override
    public OrderVO queryCourseOrder(String orderNo) {
        OrderVO orderVO = new OrderVO();
        if (StringUtils.isBlank(orderNo)) {
            return orderVO;
        }

        LambdaQueryWrapper<Order> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Order::getOrderNo, orderNo);
        Order order = orderMapper.selectOne(wrapper);
        if (order == null) {
            return orderVO;
        }

        BeanUtils.copyProperties(order, orderVO);
        return orderVO;
    }

    /**
     * 查询课程是否已经购买(在Order表中，根据会员id和课程id可以判断出是否已经购买了课程)
     *
     * @param courseId
     * @param token
     * @return
     */
    @Override
    public boolean queryCourseIsPurchase(String courseId, String token) {
        // 从token获取会员id
        String memberId = null;
        try {
            memberId = JwtUtils.getMemberIdByJwtToken(token);
        } catch (Exception e) {
            throw new GuliException(20001, "Token无效，请重新登录！");
        }
        if (StringUtils.isBlank(memberId)) {
            return false;
        }
        // 查询数据库
        LambdaQueryWrapper<Order> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Order::getCourseId, courseId)
                .eq(Order::getMemberId, memberId);
        Order order = orderMapper.selectOne(wrapper);
        // 订单存在且已支付
        if (order != null && order.getStatus() == OrderConstUtils.ORDER_PAID) {
            return true;
        } else {
            return false;
        }
    }
}
